package qualomelhor.server;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import qualomelhor.database.Usuario;
import qualomelhor.database.ParametrosSistema.OrigemLogin;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

public class CallbackTwitterServlet extends HttpServlet {
    private static final long serialVersionUID = 1657390011452788111L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	System.out.println("callback twitter chamado!!!!!");
        Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
        RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
        String verifier = request.getParameter("oauth_verifier");

        System.out.println("verifier = " + verifier);
        AccessToken acessToken = null;
        try {
            acessToken = twitter.getOAuthAccessToken(requestToken, verifier);
            request.getSession().removeAttribute("requestToken");
        } catch (TwitterException e) {
            throw new ServletException(e);
        }

        System.out.println("AccessToken = " + acessToken.toString());

        try {
			System.out.println("user id = " + twitter.getId());
		} catch (IllegalStateException e) {
			System.out.println("erro user id !!!!!!!");
			e.printStackTrace();
		} catch (TwitterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        try {
			System.out.println("screen name = " + twitter.getScreenName());
		} catch (IllegalStateException e) {
			System.out.println("erro screen name !!!!!!!");
			e.printStackTrace();
		} catch (TwitterException e) {
			System.out.println("erro screen name !!!!!!!");
			e.printStackTrace();
		}

        try {
        	User user = twitter.showUser(twitter.getScreenName());
			System.out.println("user name = " + user.getName());
			System.out.println("user image = " + user.getProfileImageURL());

			//Verificar se o usuario existe na base e adicionar caso nao exista
			DAO d = new DAO();
			Usuario u = d.getUsuarioTwitter(String.valueOf(twitter.verifyCredentials().getId()));
			if (u == null) {
				System.out.println("novo usuario do twitter sendo criado..");
				u = new Usuario("", String.valueOf(user.getId()), OrigemLogin.TWITTER.getSiteOrigem(), verifier, "", user.getName(), user.getLocation(), "", user.getLang(), "", true, user.getProfileImageURL().toString(), new Date());
			} else {
				System.out.println("atualizando usuario do twitter..");
				u.setAccessToken("<TK>" + acessToken.getToken() + "</TK><TKS>" + acessToken.getTokenSecret() + "</TKS>");
				u.setUrlImageProfile(user.getProfileImageURL().toString());
			}
			d.gravaNovoUsuario(u);

			HttpSession session = request.getSession(true);

			@SuppressWarnings("unchecked")
			HashMap<String, Object> mapSession = (HashMap<String, Object>)session.getAttribute("SESSIONVAR"); 

			mapSession.put("USUARIOATUAL", u);
			session.setAttribute("SESSIONVAR", mapSession);
			session.setAttribute("USUARIOATUAL", u);
			System.out.println("SETOU O USUARIO ATUAL: " + u.getNomeUsuario() + ", Admin:" + u.getAdmin());

			String tweet = (String)session.getAttribute("tweetComment");
			if (tweet != null) {
				System.out.println("vai postar o tweet: " + tweet);
	    		Status status = twitter.updateStatus(tweet);
	    		System.out.println("Successfully updated the status to [" + status.getText() + "].");
	    		session.removeAttribute("tweetComment");
			}

			//response.sendRedirect("/logado.jsp?nome=" + u.getNomeUsuario() + "&id=" + user.getId() + "&twitterurl=" + URLEncoder.encode(user.getProfileImageURL().toString(), "UTF-8"));
			response.sendRedirect("/");

		} catch (IllegalStateException e) {
			System.out.println("erro screen name !!!!!!!");
			e.printStackTrace();
		} catch (TwitterException e) {
			System.out.println("erro screen name !!!!!!!");
			e.printStackTrace();
		}

        System.out.println("Fim!!");
        //response.sendRedirect(request.getContextPath() + "/");
    }
}